//
//  TXFHomeTableViewController.swift
//  weibo飞飞
//
//  Created by 田侠飞 on 16/6/23.
//  Copyright © 2016年 田侠飞. All rights reserved.
//

import UIKit


private let cellidentifier = "cellidentifier"
class TXFHomeTableViewController: BasicTableViewController {
    
    //全局的
    
   var StatuesArray: [TXFStatues] =  [TXFStatues]()
    
    //上拉刷新
    
    let refresh = TXFReflesh()
    override func viewDidLoad() {
        super.viewDidLoad()
        if !isLogin {
            
            basicView?.setupBasicViewInfo(nil, title: nil)
            return
            
            
        }
        setupTableViewInfo()
        
 
        loadDataFromWeiBo(activityView.isAnimating())
        
        loadUnReadDataFromNetwork()
        
        let timer : NSTimer = NSTimer(timeInterval: 5, target: self, selector: "loadUnReadDataFromNetwork", userInfo: nil, repeats: true)
        timer.fire()
        
        NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
        //创建个控件:
        
        self.tabBarItem.badgeValue = "\(15)"
       
    }
    
    private lazy var activityView: UIActivityIndicatorView = {
        
        let view2 = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        
        view2.color = UIColor.brownColor()
        
        return view2
    }()
    
    func setupTableViewInfo(){
        // 获取class  格式: 类名.self
         tableView.registerClass(TXFStatuesCell.self, forCellReuseIdentifier: cellidentifier)
        // 指定tableViewCell 高度
        // 自动计算行高UITableViewAutomaticDimension
        tableView.rowHeight = UITableViewAutomaticDimension
        // 预估行高(预估行高越接近真实高度越好)
        tableView.estimatedRowHeight = 200
        tableView.separatorStyle = .None
        tableView.tableFooterView = activityView
        
      
        tableView.addSubview(refresh)
        //添加事件
        
        refresh.addTarget(self, action: "refreshAction", forControlEvents: UIControlEvents.ValueChanged)
        
    }
    //上拉刷新方法
    func refreshAction(){
    
    loadDataFromWeiBo(activityView.isAnimating())
    
    }
    
    func endRefreshing(){
    self.refresh.endRefreshuing()
    self.activityView.stopAnimating()
    
    }

}
extension TXFHomeTableViewController{
    
    //获取未读数据
    
    func loadUnReadDataFromNetwork(){
    
    
    
    TXFNetworkTools.shareTools.unReadCountData({ (response) -> () in
        
        guard let res = response as? [String: AnyObject] else{
            
            return
        }
        let unReadCount = TXFUnReadCount(dict: res)
        
        if unReadCount.status != 0{
        self.tabBarItem.badgeValue  = "\(unReadCount.status)"
            
            UIApplication.sharedApplication().applicationIconBadgeNumber = unReadCount.status
        }else{
        
        self.tabBarItem.badgeValue = nil
        UIApplication.sharedApplication().applicationIconBadgeNumber = 0
        
        }
        
        }) { (error) -> () in
            
        }
    
      
        
    
    }

//获取网络数据:

    private func loadDataFromWeiBo(pullUp: Bool){
    
    
        var since_id: Int64 = 0
        var  max_id: Int64 = 0
        
        
        
        if pullUp{
        //上拉刷新
        max_id = StatuesArray.last?.id ?? 0
            
            if max_id > 0{
            
            
            max_id += 1
            
            }
        }else{
        //下拉刷新
        since_id = StatuesArray.first?.id ?? 0
        
        }
        
    //直接调用网络中的单例:
        TXFNetworkTools.shareTools.homeLoadUserInfo(since_id, max_id: max_id, success: { (response) -> () in
            self.endRefreshing()
        
            
            guard let res = response?["statuses"]as? [[String: AnyObject]] else {
                                    return
                        }
                       //字典转模型
                        //可变数组
            
                       var tempArray : [TXFStatues] = [TXFStatues]()
            
                       for dic in res {
            
                       let  statues = TXFStatues(dict: dic)
               
                       tempArray.append(statues)
            }
           
            
       
            //判断上拉还是下拉
            
            if pullUp{
            
                self.StatuesArray = self.StatuesArray + tempArray
                self.tabBarItem.badgeValue = nil

            
            }else{
            
               self.StatuesArray = tempArray + self.StatuesArray
            }
            
               
            
               self.tableView.reloadData()
            
                        }) { (error) -> () in
            
            
                    print(error)
                            
                    }

    }
}

extension TXFHomeTableViewController{


//数据源方法
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return StatuesArray.count ?? 0
        
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        
        let cell = tableView.dequeueReusableCellWithIdentifier(cellidentifier, forIndexPath: indexPath)as? TXFStatuesCell

        
        cell!.status = StatuesArray[indexPath.row]
        
        
        
        return cell!
    }

    
    override func  tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
       
        
        
        if StatuesArray.count == indexPath.row + 1 && !activityView.isAnimating()
        {
        
        activityView.startAnimating()
        
        loadDataFromWeiBo(activityView.isAnimating())
        }
        
        
    }
    
    
}







